package com.liqin.nothing.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.liqin.nothing.ai.TongYiClient;
import com.liqin.nothing.service.SseService;
import com.liqin.nothing.service.TongYiService;
import io.reactivex.Flowable;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author gonghl
 * @since 2024/8/12 下午 3:01
 */
@Service
@RequiredArgsConstructor
public class TongYiServiceImpl implements TongYiService {

    private final TongYiClient tongYiClient;
    private final SseService sseService;

    @Override
    public SseEmitter init(String id) {
        // 获取SSE连接
        return sseService.connect(id);
    }

    @Override
    public void chat(String id, String message) {
        // 通义千问对话
        Flowable<GenerationResult> flowable = tongYiClient.sendMessage(message);
        // 逐字发送
        flowable.blockingForEach(generationResult -> sseService.sendPrivate(id, generationResult.getOutput().getChoices().get(0).getMessage().getContent()));
    }

}
